package com.example.zheng.qq.fragment;


import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.zheng.qq.R;
import com.example.zheng.qq.adapter.InfoAdapter;
import com.example.zheng.qq.entity.Information;
import com.example.zheng.qq.entity.UseName;
import com.example.zheng.qq.util.ContextApplication;
import com.example.zheng.qq.util.Util;
import com.example.zheng.qq.view.Circle1;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StartDrawer extends Fragment {
    private List<Information> list = new ArrayList<>();
    private LinearLayout linearLayout;
    private View v;
    private ViewGroup mContainer;
    private ImageView imageView;
    private ImageView imageView1;
    private TextView editor;
    public static  UseName useName;
    private SQLiteDatabase mDb = Util.Db;
    private  Bitmap head;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor1;
    public StartDrawer(){
        super();
    }

    public static void init(UseName useName1){
       useName=useName1;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("qq","onCreateView");
        sharedPreferences= ContextApplication.getContext().getSharedPreferences("data1", Context.MODE_PRIVATE);
        editor1=sharedPreferences.edit();
        mContainer = container;
        v = inflater.inflate(R.layout.start_drawer, container, false);
        initList();
        InfoAdapter infoAdapter = new InfoAdapter(container.getContext(), R.layout.infor_item, list);
        ListView listView = (ListView) v.findViewById(R.id.infomation);
        imageView = (ImageView) v.findViewById(R.id.headImage);
        imageView1 = (ImageView) v.findViewById(R.id.QrCode);
        editor=(TextView)v.findViewById(R.id.editor);
        Bitmap bitmap = QrCodeImage("http://www.baidu.com", 40, 40);
        try {
            head = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(Uri.parse(useName.getHeadPicture())));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap h=BitmapFactory.decodeResource(getResources(),R.drawable.qq);
        Bitmap b=addLogo(bitmap,h);
        imageView1.setImageBitmap(b);
        listView.setDivider(null);
        listView.setAdapter(infoAdapter);
        scanningImage();

        return v;
    }

    //给二维码添加图片
    private Bitmap addLogo(Bitmap bitmap, Bitmap head) {
        int bitmapWidth=bitmap.getWidth();
        int bitmapHeight=bitmap.getHeight();
        int headWidth=head.getWidth();
        int headHeight=head.getHeight();
        Bitmap blankBitmap=Bitmap.createBitmap(bitmapWidth,bitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(blankBitmap);
        canvas.drawBitmap(bitmap,0,0,null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        float scal=1.0f;
        while((headWidth/scal)>(bitmapWidth/5)||(headHeight/scal)>(bitmapHeight/5)){
            scal*=2;
        }
//        float sx=1.0f/scal;
        float sx=headWidth*1.0f/5/headWidth;
        canvas.scale(sx,sx,headWidth/2,headHeight/2);
        canvas.drawBitmap(head,(bitmapWidth-headWidth)/2,(bitmapHeight-headHeight)/2,null);
        canvas.restore();
        Log.d("qq","添加图片");
        return blankBitmap;
    }

    /**
     * 二维码的生成
     * @param content 二维码的内容
     * @param width  二维码的宽度
     * @param height
     * @return
     */
    private Bitmap QrCodeImage(String content, int width, int height) {
        if(content==null||"".equals(content)||content.length()<1){
            return null;
        }

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    //当这个字节矩阵有值时，则给这个数组像素点设置为黑色，反之为白色
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  解析QR图，扫描二维码，将扫描出来的结果放在签名处
      */

    private void scanningImage() {
        Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        // 获得待解析的图片
        Bitmap scanBitmap = ((BitmapDrawable) imageView1.getDrawable()).getBitmap();
        int width = scanBitmap.getWidth();
        int height = scanBitmap.getHeight();
        int[] pixels = new int[width * height];
        scanBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        RGBLuminanceSource source=new RGBLuminanceSource(width,height,pixels);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result;
        try {
            result = reader.decode(bitmap1, hints);
            // 得到解析后的文字
            editor.setText(result.getText());
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onStart() {
        String name=useName.getName();
        Util.SqlPictureId(name,imageView);
        super.onStart();
        Log.d("qq","onStart");

    }

    public void initList(){
        for(int i=0;i<6;i++) {
            Information information = new Information(R.drawable.about2, "了解会员特权");
            list.add(information);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("dd","滑动布局被摧毁了");
//        editor1.putString("usename",useName);

    }


}
